<script setup>
import SearchComponent from '@/components/SearchComponent/SearchComponent.vue'
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getSceneryDataService, getHotelDataService, getRestaurantDataService, getPostDataService } from '@/apis/list.js'
import ListContent from '@/ComprehensivePackage/List/components/ListContent.vue'
import { throttle } from 'lodash'
import { formatTime } from '@/utils/formatTime.js'

// 列表展示的数据类型
const type = ref('')

// 分段器当前的index索引值
const activeIndex = ref(0)

// 页面滑动到底部时的加载状态
const status = ref('loadmore')

// 初始化筛选条件
const query = ref({
	page: 1,
	pageSize: 5,
	filter_type: '',
	sort: 'comprehensive',
	grade: '',
	is_hot: '',
	city_id: ''
})

// 获取子组件实例对象
const listContent = ref(null)

// 存储获取到的列表数据
const list = ref([])

// 存储获取到的列表数据总数
const count = ref(null)

// 分段器列表
const sectionList = ref([
	{ name: '景点', value: 'scenery' },
	{ name: '酒店', value: 'hotel' },
	{ name: '餐厅', value: 'restaurant' },
	{ name: '攻略', value: 'post' }
])

// 解决吸顶遮挡问题
const is_open = ref(false)

// 公共的筛选项
const sort_option = ref([
	{
		label: '综合排序',
		value: 'comprehensive'
	},
	{
		label: '按价格由低 → 高',
		value: 'price_low_high'
	},
	{
		label: '按价格由高 → 低',
		value: 'price_high_low'
	},
	{
		label: '按评分由高 → 低',
		value: 'rating_high_low'
	},
	{
		label: '按评分由低 → 高',
		value: 'rating_low_high'
	}
])

const generateGradeOption = (type) => {
	let array = []
	for (let i = 1; i <= 5; i++) {
		array[i - 1] = {
			label: i + (type === '景点' ? 'A' : '星'),
			value: i + (type === '景点' ? 'A' : '星')
		}
	}
	return [
		...array,
		{
			label: `普通${type}`,
			value: `普通${type}`
		}
	]
}

const generateHotOption = (type) => {
	return [
		{
			label: `热门${type}`,
			value: 1
		},
		{
			label: `特色${type}`,
			value: 0
		}
	]
}

// 景点筛选项
// Dropdown下拉菜单需要的绑定值
const scenery_filter = ref({
	value1: '',
	value2: 'comprehensive',
	value3: '',
	value4: null,
	options1: [
		{
			label: '城市观光',
			value: '城市观光'
		},
		{
			label: '人文古迹',
			value: '人文古迹'
		},
		{
			label: '自然风光',
			value: '自然风光'
		},
		{
			label: '网红打卡',
			value: '网红打卡'
		},
		{
			label: '展览展馆',
			value: '展览展馆'
		}
	],
	options2: sort_option.value,
	options3: generateGradeOption('景点'),
	options4: generateHotOption('景点')
})

// 酒店筛选项
// Dropdown下拉菜单需要的绑定值
const hotel_filter = ref({
	value1: '',
	value2: 'comprehensive',
	value3: '',
	value4: null,
	options1: [
		{
			label: '经济型',
			value: '经济型'
		},
		{
			label: '特惠型',
			value: '特惠型'
		},
		{
			label: '豪华型',
			value: '豪华型'
		},
		{
			label: '民宿',
			value: '民宿'
		},
		{
			label: '公寓',
			value: '公寓'
		}
	],
	options2: sort_option.value,
	options3: generateGradeOption('酒店'),
	options4: generateHotOption('酒店')
})

// 餐厅筛选项
// Dropdown下拉菜单需要的绑定值
const restaurant_filter = ref({
	value1: '',
	value2: 'comprehensive',
	value4: null,
	options1: [
		{
			label: '中餐',
			value: '中餐'
		},
		{
			label: '西餐',
			value: '西餐'
		},
		{
			label: '特色小吃',
			value: '特色小吃'
		},
		{
			label: '自助餐',
			value: '自助餐'
		},
		{
			label: '快餐',
			value: '快餐'
		}
	],
	options2: sort_option.value,
	options3: generateHotOption('餐厅')
})

// 攻略筛选项
// Dropdown下拉菜单需要的绑定值
const post_filter = ref({
	value1: '',
	value4: null,
	options1: [
		{
			label: '景点',
			value: 'scenery'
		},
		{
			label: '酒店',
			value: 'hotel'
		},
		{
			label: '餐厅',
			value: 'restaurant'
		}
	],
	options2: generateHotOption('攻略')
})

// 获取景点数据
const getSceneryData = async (is_push) => {
	const res = await getSceneryDataService(query.value)
	if (list.value.length > 0 && is_push) {
		list.value = [...list.value, ...res.data]
	} else {
		list.value = res.data
	}

	if (res.data.length === 0 || res.data.length < 5) {
		status.value = 'nomore'
	} else {
		// 存储数据总数
		count.value = res.count
	}
}

// 获取酒店数据
const getHotelData = async (is_push) => {
	const res = await getHotelDataService(query.value)
	if (list.value.length > 0 && is_push) {
		list.value = [...list.value, ...res.data]
	} else {
		list.value = res.data
	}

	if (res.data.length === 0 || res.data.length < 5) {
		status.value = 'nomore'
	} else {
		// 存储数据总数
		count.value = res.count
	}
}

// 获取餐厅数据
const getRestaurantData = async (is_push) => {
	const res = await getRestaurantDataService(query.value)
	if (list.value.length > 0 && is_push) {
		list.value = [...list.value, ...res.data]
	} else {
		list.value = res.data
	}

	if (res.data.length === 0 || res.data.length < 5) {
		status.value = 'nomore'
	} else {
		// 存储数据总数
		count.value = res.count
	}
}

// 获取攻略数据
const getPostData = async (is_push) => {
	const res = await getPostDataService(query.value)

	// 格式化发布时间
	res.data?.map((item) => (item.createdAt = formatTime(item.createdAt)))

	if (list.value.length > 0 && is_push) {
		list.value = [...list.value, ...res.data]
	} else {
		list.value = res.data
	}

	if (res.data.length === 0 || res.data.length < 5) {
		status.value = 'nomore'
	} else {
		// 存储数据总数
		count.value = res.count
	}
}

// 根据接收到的页面类型加载不同的列表数据
const loadTypeData = (type, is_push) => {
	switch (type) {
		case 'scenery':
			getSceneryData(is_push)
			break
		case 'hotel':
			getHotelData(is_push)
			break
		case 'restaurant':
			getRestaurantData(is_push)
			break
		case 'post':
			getPostData(is_push)
			break
	}
}

// 子组件列表滑动到底部加载下一页数据
const handleReachBottom = () => {
	if (query.value.page >= Math.ceil(count.value / query.value.pageSize)) {
		if (status.value != 'nomore') {
			status.value = 'nomore'
		}
		return
	}
	status.value = 'loading'
	// 页码增加
	query.value.page++

	if (type.value) {
		loadTypeData(type.value, true)
	} else {
		switch (activeIndex.value) {
			case 0:
				getSceneryData(true)
				break
			case 1:
				getHotelData(true)
				break
			case 2:
				getRestaurantData(true)
				break
			case 3:
				getPostData(true)
				break
		}
	}

	setTimeout(() => {
		if (query.value.page >= Math.ceil(count.value / query.value.pageSize)) {
			status.value = 'nomore'
		} else {
			status.value = 'loading'
		}
	}, 2000)
}

// 创建节流函数实例,对滚动加载函数进行节流处理
const throttledLoadData = throttle(handleReachBottom, 1000)

// 分段器切换
const onSectionChange = (index) => {
	// 分段器切换索引值更新
	activeIndex.value = index

	// 分段器切换页码重置为1
	query.value.page = 1

	// 根据分段器索引重新发送请求更新数据
	switch (index) {
		case 0:
			list.value = []
			getSceneryData(false)
			break
		case 1:
			list.value = []
			getHotelData(false)
			break
		case 2:
			list.value = []
			getRestaurantData(false)
			break
		case 3:
			list.value = []
			getPostData(false)
			break
	}

	// 调用子组件方法使得分段器切换时回到顶部
	listContent.value.goToTop()
}

// 映射不同的type对应的筛选项对象
const mapFilter = {
	scenery: scenery_filter.value,
	hotel: hotel_filter.value,
	restaurant: restaurant_filter.value,
	post: post_filter.value
}

// 筛选条件切换
const onChange = () => {
	// 更新筛选条件
	query.value.filter_type = mapFilter[type.value].value1
	query.value.sort = mapFilter[type.value].value2
	query.value.grade = mapFilter[type.value].value3
	query.value.is_hot = mapFilter[type.value].value4 === null ? '' : mapFilter[type.value].value4

	query.value.page = 1

	// 发送请求更新数据
	loadTypeData(type.value, false)

	// 返回顶部
	listContent.value.goToTop()
}

// 页面初始化时接收传递的参数
onLoad((option) => {
	if (option.type) {
		// 记录接收到的页面类型
		type.value = option.type

		// 选择当前类型对应的筛选项
		const currentFilter = mapFilter[option.type]

		// 判断是否存在筛选条件
		if (option.filter_type) {
			query.value.filter_type = option.filter_type
			currentFilter.value1 = option.filter_type
		}

		// 判断是否需要筛选热门产品
		if (option.is_hot) {
			query.value.is_hot = option.is_hot
			currentFilter.value4 = option.is_hot
		}

		// 加载页面数据,发送请求
		loadTypeData(type.value, false)
	}

	if (option.city_id) {
		query.value.city_id = option.city_id
		getSceneryData()
	}
})
</script>

<template>
	<view class="container">
		<view class="top">
			<!-- 搜索框 -->
			<SearchComponent></SearchComponent>

			<view class="filter" :style="{ overflow: is_open ? '' : 'hidden' }">
				<!-- 景点筛选菜单 -->
				<up-dropdown v-if="type === 'scenery'" menu-icon="arrow-down-fill" inactive-color="#000000" title-size="15" @open="is_open = true" @close="is_open = false">
					<up-dropdown-item v-model="scenery_filter.value1" title="筛选" :options="scenery_filter.options1" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="scenery_filter.value2" title="综合排序" :options="scenery_filter.options2" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="scenery_filter.value3" title="景点等级" :options="scenery_filter.options3" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="scenery_filter.value4" title="热门推荐" :options="scenery_filter.options4" @change="onChange"></up-dropdown-item>
				</up-dropdown>

				<!-- 酒店筛选菜单 -->
				<up-dropdown v-else-if="type === 'hotel'" menu-icon="arrow-down-fill" inactive-color="#000000" title-size="15" @open="is_open = true" @close="is_open = false">
					<up-dropdown-item v-model="hotel_filter.value1" title="筛选" :options="hotel_filter.options1" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="hotel_filter.value2" title="综合排序" :options="hotel_filter.options2" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="hotel_filter.value3" title="酒店星级" :options="hotel_filter.options3" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="hotel_filter.value4" title="热门推荐" :options="hotel_filter.options4" @change="onChange"></up-dropdown-item>
				</up-dropdown>

				<!-- 餐厅筛选菜单 -->
				<up-dropdown v-else-if="type === 'restaurant'" menu-icon="arrow-down-fill" inactive-color="#000000" title-size="15" @open="is_open = true" @close="is_open = false">
					<up-dropdown-item v-model="restaurant_filter.value1" title="筛选" :options="restaurant_filter.options1" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="restaurant_filter.value2" title="综合排序" :options="restaurant_filter.options2" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="restaurant_filter.value4" title="热门推荐" :options="restaurant_filter.options3" @change="onChange"></up-dropdown-item>
				</up-dropdown>

				<!-- 攻略筛选菜单 -->
				<up-dropdown v-else-if="type === 'post'" menu-icon="arrow-down-fill" inactive-color="#000000" title-size="15" @open="is_open = true" @close="is_open = false">
					<up-dropdown-item v-model="post_filter.value1" title="筛选" :options="post_filter.options1" @change="onChange"></up-dropdown-item>
					<up-dropdown-item v-model="post_filter.value4" title="热门推荐" :options="post_filter.options2" @change="onChange"></up-dropdown-item>
				</up-dropdown>

				<!-- 目的地页进入时使用分段器展示数据 -->
				<up-subsection v-else :list="sectionList" :current="0" @change="onSectionChange"></up-subsection>
			</view>
		</view>

		<view class="content">
			<ListContent :status="status" :type_key="type ? type : sectionList[activeIndex].value" :list="list" @reachBottom="throttledLoadData" ref="listContent"></ListContent>
		</view>
	</view>
</template>

<style lang="scss" scoped>
.container {
	background-color: #fff;
	display: flex;
	flex-direction: column;

	.top {
		position: sticky;
		top: 0;
		left: 0;
		z-index: 99;
		border-bottom: 2rpx solid #f5f5f5;
		background-color: #fff;
		padding: 20rpx;
	}
}
</style>
